package com.jintoufs.web.action.scene;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jhj.common.util.JhjResponseUtil;
import com.jintoufs.dao.QueryFilters;
import com.jintoufs.dao.QueryRule;
import com.jintoufs.domain.hotel.Hotel;
import com.jintoufs.domain.region.Region;
import com.jintoufs.domain.scene.Scene;
import com.jintoufs.logAnnotation.SystemControllerLog;
import com.jintoufs.service.region.RegionService;
import com.jintoufs.service.scene.SceneService;
import com.jintoufs.util.valid.ValidUtil;
import com.jintoufs.util.ztree.TreeNode;
import com.jintoufs.web.action.support.JqgridPage;
import com.jintoufs.web.action.support.SupportAction;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jintoufs.util.ResponseUtil.writeInfo;

/**
 * Created by xufei on 2017/12/29.
 */
@Controller
@Scope("prototype")
@RequestMapping("/scene")
public class SceneAction extends SupportAction {

    @Resource
    private SceneService sceneService;


    @Resource
    private RegionService regionService;

    /**
     * 审核通过鱼·定制信息查询
     * @return
     * @throws IOException
     */
    @RequestMapping("/list")
    public String list() throws IOException {
        return "scene/list";
    }
    /**
     * 未审核鱼·定制信息查询
     * @return
     * @throws IOException
     */
    @RequestMapping("/authlist")
    public String authList() throws IOException {
        return "scene/authlist";
    }

    @RequestMapping("/query")
    @ResponseBody
    public JqgridPage query(String status,String op,int page, int rows, String sidx, String sord, String filters) {
        PageHelper.startPage(page, rows);
        QueryFilters filters_ = null;
        if (filters == null || filters.trim().isEmpty()) {
            filters_ = new QueryFilters();
        } else {
            filters_ = JSON.parseObject(filters, QueryFilters.class);
        }
        if (!ValidUtil.isEmpty(status)){
            QueryRule role = new QueryRule();
            role = new QueryRule();
            role.setOp(op);
            role.setField("s.status");
            role.setData(status);
            filters_.getRules().add(role);
        }
        filters_.setSidx(sidx);
        filters_.setSord(sord);
        List<Map<String,Object>> list = sceneService.getByFilter(filters_);
        // 用PageInfo对结果进行包装
        PageInfo pageInfo = new PageInfo(list);
        return new JqgridPage(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getPageNum(),
                pageInfo.getList());
    }

    /**
     * input.do?id= 进入活动编辑与新增页面 <br>*
     * @param id    活动Id
     * @param model
     * @return
     */
    @RequestMapping(value = "input", method = RequestMethod.GET)
    public String input(String id, Model model) {
        Region region = null;
        Map<String,Object> map = new HashMap<>();
        // 是否为编辑保存
        Boolean isEdit = false;

        if (id != null) {
            // 修改
            Map<String, Object> params = new HashMap<>();
            params.put("id", id);
            List<Map<String,Object>> list = sceneService.findByScene(params);

            if (list != null && list.size() > 0) {
                map = list.get(0);
                region = regionService.queryById(Short.valueOf(map.get("regionId").toString()));
            }
            isEdit = true;
        } else {
            // 新增
        }
        List<TreeNode> list = regionService.getModuleTree(region);
        model.addAttribute("ztreeNodes",JSON.toJSONString(list));
        model.addAttribute("isEdit", isEdit);
        model.addAttribute("entity", map);
        return "scene/input";
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    @SystemControllerLog(description = "新增鱼·定制")
    public void save(Scene scene, HttpServletResponse response) throws ParseException {

        Map<String, Object> result;
        String error = null;
        if(scene.getSceneName() == null && "".equals(scene.getSceneName())){
            error = "鱼·定制名字不能为空！";
        }
        if(scene.getAddress() == null && "".equals(scene.getAddress())){
            error = "详细地址不能为空！";
        }

        DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time=format.format(new Date());
        if (ValidUtil.isEmpty(scene.getId())){
            scene.setCreateTime(format.parse(time));
            scene.setStatus("0");
        }
        scene.setModifyTime(format.parse(time));
        if (ValidUtil.isEmpty(scene.getId())){
            result = sceneService.insert(scene,getUUID());
        }else {
            result = sceneService.insert(scene,null);
        }
        JhjResponseUtil.responseJson(response, JSON.toJSONString(result));
    }


    @RequestMapping("edit")
    @SystemControllerLog(description = "修改鱼·定制信息")
    public void edit(Scene scene, HttpServletResponse response) {
        Map<String, Object> result = sceneService.insert(scene,null);
        JhjResponseUtil.responseJson(response, JSON.toJSONString(result));
    }



    @RequestMapping("delete")
    @SystemControllerLog(description = "删除鱼·定制信息")
    public void delete(HttpServletResponse response, String[] id) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            for (String _id:id){
                sceneService.delete(_id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof DataIntegrityViolationException) {
                ajaxMsg.setCode("500");
                ajaxMsg.setMessage("该鱼·定制在营业中，删除失败！");
            }
        }
        writeInfo(response, JSON.toJSONString(ajaxMsg));
    }

    /**
     * 获取详细信息
     */
    @RequestMapping("/getDetail")
    @SystemControllerLog(description = "查看鱼·定制详细信息")
    public String getDetail(String id, Model model) {
        Map<String,Object> result = new HashMap<>();
        if (!ValidUtil.isEmpty(id)) {
            result = sceneService.getById(id);
        }
        model.addAttribute("entity", result);
        model.addAttribute("isEdit", "view");
        model.addAttribute("title", "鱼·定制详细信息");
        return "scene/detail";
    }


    @RequestMapping("unlock")
    @ResponseBody
    public AjaxMsg unlock(String id,String type){
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
           Scene scene= sceneService.selectByPrimaryKey(id);
            scene.setStatus(type);
           sceneService.update(scene);
            ajaxMsg.setMessage("操作成功。");
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("操作失败");
        }
        return ajaxMsg;
    }

    @RequestMapping("setRecommend")
    @ResponseBody
    public AjaxMsg setRecommend(String id){
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            Scene scene= sceneService.selectByPrimaryKey(id);
            if("0".equals(scene.getRecommend())){
                scene.setRecommend("1");
            }else{
                scene.setRecommend("0");
            }
            sceneService.update(scene);
            ajaxMsg.setMessage("操作成功。");
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("操作失败");
        }
        return ajaxMsg;
    }
}
